#include "StdAfx.h"
#include "GrfUtil.h"
extern "C"
{
#include "grf.h"
}

GrfUtil::GrfUtil(void)
{
}

GrfUtil::~GrfUtil(void)
{
}


int GrfUtil::ExtractFileFromGrf(LPCTSTR grfName, LPCTSTR grfFileName, LPCTSTR fileName)
{
	char lpGrfName[MAX_PATH];
	char lpGrfFileName[MAX_PATH];
	char lpFileName[MAX_PATH];
	WideCharToMultiByte(CP_ACP,NULL,grfName,-1,lpGrfName,sizeof(lpGrfName)/sizeof(lpGrfName[0]),NULL,FALSE);
	WideCharToMultiByte(CP_ACP,NULL,grfFileName,-1,lpGrfFileName,sizeof(lpGrfFileName)/sizeof(lpGrfFileName[0]),NULL,FALSE);
	WideCharToMultiByte(CP_ACP,NULL,fileName,-1,lpFileName,sizeof(lpFileName)/sizeof(lpFileName[0]),NULL,FALSE);

	GrfError error;
	Grf * grf = grf_callback_open((const char*)lpGrfName, "rb", &error, NULL);
	int result = grf_extract(grf, (const char*)lpGrfFileName, (const char*)lpFileName, &error);
	grf_free(grf);
	return result;
}

void GrfUtil::BatchExtractFilesFromGrf(LPCTSTR grfName, int fileCount, ... )
{
	char lpGrfName[MAX_PATH];
	char lpFileName[MAX_PATH];
	WideCharToMultiByte(CP_ACP,NULL,grfName,-1,lpGrfName,sizeof(lpGrfName)/sizeof(lpGrfName[0]),NULL,FALSE);
	GrfError error;
	Grf * grf = grf_callback_open((const char*)lpGrfName, "rb", &error, NULL);

	va_list argp;
	va_start(argp, fileCount);
	for (int i = 0; i < fileCount; ++i)
	{
		WideCharToMultiByte(CP_ACP,NULL,va_arg(argp,LPCTSTR),-1,lpFileName,sizeof(lpFileName)/sizeof(lpFileName[0]),NULL,FALSE);
		grf_extract(grf, (const char*)lpFileName, (const char*)lpFileName, &error);
	}
	va_end(argp);
	grf_free(grf);
}

void GrfUtil::ExtractDirectory(LPCTSTR grfName, LPCTSTR grfDirectory)
{
	char lpGrfName[MAX_PATH];
	char lpGrfDirectory[MAX_PATH];
	WideCharToMultiByte(CP_ACP,NULL,grfName,-1,lpGrfName,sizeof(lpGrfName)/sizeof(lpGrfName[0]),NULL,FALSE);
	WideCharToMultiByte(CP_ACP,NULL,grfDirectory,-1,lpGrfDirectory,sizeof(lpGrfDirectory)/sizeof(lpGrfDirectory[0]),NULL,FALSE);
	GrfError error;
	Grf * grf = grf_callback_open((const char*)lpGrfName, "rb", &error, NULL);
	for (uint32_t i = 0; i < grf->nfiles; i++)
	{
		if (strstr(grf->files[i].name, lpGrfDirectory) != NULL)
		{
			grf_extract(grf, grf->files[i].name, grf->files[i].name, &error);
		}
	}
	grf_free(grf);
}

void GrfUtil::CreateFullDirectory(LPCTSTR directory)
{

	_TCHAR *token = NULL;  
	_TCHAR *next_token = NULL;
	_TCHAR tempPath[MAX_PATH];
	_TCHAR fullDirectory[MAX_PATH];

	ZeroMemory(tempPath, MAX_PATH);
	_tcscpy_s(fullDirectory, MAX_PATH, directory);

	token = _tcstok_s(fullDirectory, TEXT("\\"), &next_token);  
	while (token != NULL)  
	{    
		_tcscat_s(tempPath, MAX_PATH, token);
		
		WIN32_FIND_DATA   wfd;
		HANDLE hFind = FindFirstFile(tempPath, &wfd);
		if ((hFind == INVALID_HANDLE_VALUE) || (!(wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)))
		{
			CreateDirectory(tempPath, NULL);
		}
		_tcscat_s(tempPath, MAX_PATH, TEXT("\\"));

		token = _tcstok_s(NULL, TEXT("\\"), &next_token);  
	}  
}